package weathers

import (
	"encoding/json"
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"io/ioutil"
	"net/http"
	"net/url"
)

// QWeatherApi 和风天气api
// 文档地址： https://dev.qweather.com/docs/api/weather/weather-now/
type QWeatherApi struct {
	apiKey string
}

func NewQWeatherApi(apiKey string) *QWeatherApi {
	return &QWeatherApi{
		apiKey: apiKey,
	}
}

func (wea *QWeatherApi) WeatherNow(req dto.WeatherRequest) (dto.WeatherInfo, error) {
	var weather dto.WeatherInfo
	weatherApiKey := wea.apiKey
	weatherBaseUrl := "https://devapi.qweather.com/v7/weather/now"

	location := fmt.Sprintf("%f,%f", req.Longitude, req.Latitude)
	// 构建请求参数
	params := url.Values{}
	params.Add("location", location)
	params.Add("key", weatherApiKey)
	params.Add("lang", "zh") // 中文响应

	// 发送GET请求
	resp, err := http.Get(fmt.Sprintf("%s?%s", weatherBaseUrl, params.Encode()))
	if err != nil {
		return weather, err
	}
	defer resp.Body.Close()

	// 读取响应
	body, _ := ioutil.ReadAll(resp.Body)
	// 解析JSON
	var result qWeatherResponse
	if err := json.Unmarshal(body, &result); err != nil {
		return weather, err
	}

	// 处理结果
	if result.Code != "200" {
		return weather, fmt.Errorf("错误代码 %s: %s", result.Code, wea.getErrorMessage(result.Code))
	}
	weather.Icon = result.Now.Icon
	weather.Temp = result.Now.Temp
	weather.Text = result.Now.Text
	return weather, nil
}

// 简单错误码映射
func (wea *QWeatherApi) getErrorMessage(code string) string {
	switch code {
	case "204":
		return "无此位置数据"
	case "401":
		return "无效API Key"
	case "404":
		return "未知错误"
	default:
		return "服务异常"
	}
}
